﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using KamLib;


namespace Ext.Net.UIS
{

    public class Store : Ext.Net.Store
    {
        public Store(Context context, TermNode termNode)
        {
            if (termNode == null)
                throw new ArgumentNullException("termNode");
            if (termNode.Term == null)
                throw new NoNullAllowedException("UIS.Store.constructor: termNode.Term is null");

            Context = context;
            TermNode = termNode;
            // ReSharper disable DoNotCallOverridableMethodsInConstructor
            ID = termNode.StoreID ?? Context.NewControlID();
            ModelName = termNode.Term.Name;
            // ReSharper restore DoNotCallOverridableMethodsInConstructor
        }

        public new readonly Context Context;
        public readonly TermNode TermNode;
        public readonly List<Term> UsingFields = new List<Term>();

        public void Using(Term term)
        {
            if (term != null)
                UsingFields.Register(term);
        }

        protected override void OnBeforeClientInit(Observable sender)
        {
            this.AddFields(TermNode, UsingFields);
            base.OnBeforeClientInit(sender);

            if (TermNode == null || TermNode.Term == null) return;

            if (TermNode.Term.Have(TermTags.Simple))
            {
                var proxy = Proxy.Primary as ServerProxy;
                if (proxy == null) return;

                var reader = proxy.Reader.Primary;
                if (reader == null)
                    proxy.Reader.Add(new ArrayReader { IDProperty = "0" });
            }

        }

        public bool IsUsing() { return UsingFields.Count > 0; }
    }



    public static class StoreHelper
    {

        public static void AddFields(this Ext.Net.Store store, TermNode node, List<Term> terms)
        {
            var model = store.Model.Primary;
            if (model == null)
            {
                store.Model.Add(model = new Model { Name = store.ModelName });
                store.ModelName = null;
            }

            model.AddFields(node, terms);
        }

    }

}
